import {Subject} from 'rxjs';
import {
  Component,
  OnInit,
  ElementRef,
  ViewChild,
  ViewEncapsulation,
  Renderer, OnDestroy
} from '@angular/core';
import {Router} from '@angular/router';

import {Content} from "@shared/components/toolbar/toolbar-content";

import {ToolsService} from "@shared/service/tools/tools.service";
import {VideoService} from "./video.service";
import {AppPlayTurn, VideoRespVO} from "@interface/index";



@Component({
  selector: 'videos',
  templateUrl: './video.component.html',
  styleUrls: ['./video.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class VideoComponent implements OnInit, OnDestroy {
  public bannerObj: AppPlayTurn[];
  public categorys: any[] = [];
  public videos: Array<VideoRespVO>;
  public isFinished = true;
  public ngUnsubscribe: Subject<void> = new Subject<void>();

  @ViewChild(Content) content;
  @ViewChild('nav') nav: ElementRef;

  constructor(public videoService: VideoService,
              public router: Router,
              public tools: ToolsService,
              public renderer: Renderer) {
  }

  /**
   * 获取轮播信息
   */
  getSliderList() {
    this.videoService.getSlider().takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0') {
        this.bannerObj = res.data.list;
      }
    });
  };

  /**
   * @description 前往视频详情
   * @author ouyqx-691
   * @date 2017/11/24
   * @param news 单个轮播对象
   */
  goToTarget(slide) {
    // 外链且存在外链url
    if (slide.linkType === 2 && slide.detailUrl) {
      window.open(slide.detailUrl);
    } else {
      this.router.navigate(['/video', slide.resId]);
    }
  }

  /**
   * 获取分类列表
   */
  getCateListInfo() {
    this.tools.showLoading();
    this.videoService.getCateList().subscribe(res => {
      if (res.result === '0') {
        this.categorys = res.data;
        const categorys = res.data,
          categorysVideo = [],
          categorysId = [];

        for (const category of categorys) {
          categorysVideo.push(category.videoRespVOList);
          categorysId.push(category.cateId);
        }
        this.videos = [].concat.apply([], categorysVideo); // 合并数组
        this.tools.hideLoading();
      }
    });
  };

  /**
   * 前往分类
   * @param category 分類ID
   */
  goToCategory(category) {
    const categoryId = category.cateId;
    this.videoService.currentCategory = category.cateName;
    this.router.navigate([`/video/category`, categoryId]);
  }

  ngOnInit() {
    this.getSliderList();
    this.getCateListInfo();
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  };
}
